<template>
  <!-- 新增项目信息 -->
  <div class="container">
    <top-head :back="true"></top-head>
    <a-form-model ref="ruleForm" :model="form" :rules="rules" v-bind="layout" class="ge-form">
      <aline name="基础信息"></aline>
      <a-row>
        <a-col :span="11">
          <a-form-model-item label="承包商项目名称" prop="name">
            <ge-input-new :config="{ disabled: isDetail, maxLength: 200 }" v-model="form.name" placeholder="请输入承包商项目名称" />
          </a-form-model-item>
        </a-col>
        <a-col :span="2"></a-col>
        <a-col :span="11">
          <a-form-model-item label="作业计划时间" prop="time">
            <ge-data-picker-new v-model="form.time" :config="{ type: 'range', disabled }" @backValue="
              (val) => {
                form.startDate = val.length
                  ? $moment(val[0]).format('YYYY-MM-DD')
                  : null;
                form.endDate = val.length
                  ? $moment(val[1]).format('YYYY-MM-DD')
                  : null;
                form.time = val.length ? val : null;
              }
            " />
          </a-form-model-item>
        </a-col>
      </a-row>
      <a-row>
        <a-col :span="11">
          <a-form-model-item label="现场负责人" prop="principal">
            <ge-input-new v-model="form.principal" :config="{ disabled }"></ge-input-new>
          </a-form-model-item>
        </a-col>
        <a-col :span="2"></a-col>
        <a-col :span="11">
          <a-form-model-item label="负责人联系电话" prop="principalPhone">
            <ge-input-new :config="{ disabled, maxLength: 200 }" v-model="form.principalPhone" placeholder="请输入负责人联系电话" />
          </a-form-model-item>
        </a-col>
      </a-row>
      <a-row>
        <a-col :span="24">
          <a-form-model-item label="施工方案" prop="program">
            <ge-rich-text-new v-model="form.program" :config="{ disabled }"></ge-rich-text-new>
          </a-form-model-item>
        </a-col>
      </a-row>
      <a-row>
        <a-col :span="24" style="margin-bottom: 20px">
          <a-form-model-item label="" prop="staff">
            <ge-child-form ref="childForm" :pagination="false" v-model="form.staff" :config="{ disabled }" title="作业人员信息"
              :columns="columns" @increase="handleIncrease" @decrease="handleDecrease"></ge-child-form>
            <p class="hint">请谨慎填写作业人员信息，填写信息后可生成施工证</p>
          </a-form-model-item>
        </a-col>
      </a-row>
      <aline name="其他资料"></aline>
      <a-row>
        <a-col :span="24">
          <a-form-model-item label="安全承诺" prop="promiseAnnex">
            <ge-file-new v-model="form.promiseAnnex" :config="{ disabled, json: true }"></ge-file-new>
          </a-form-model-item>
        </a-col>
      </a-row>
      <a-row>
        <a-col :span="24">
          <a-form-model-item label="安全告知书" prop="informAnnex">
            <ge-file-new v-model="form.informAnnex" :config="{ disabled, json: true }"></ge-file-new>
          </a-form-model-item>
        </a-col>
      </a-row>
      <a-row>
        <a-col :span="24">
          <a-form-model-item label="其他证明" prop="proveAnnex">
            <ge-file-new v-model="form.proveAnnex" :config="{ disabled, json: true }"></ge-file-new>
          </a-form-model-item>
        </a-col>
      </a-row>
      <a-row>
        <a-col :span="24">
          <a-form-model-item label="入场施工申请单" prop="admissionAnnex">
            <ge-file-new v-model="form.admissionAnnex" :config="{ disabled, json: true }"></ge-file-new>
          </a-form-model-item>
        </a-col>
      </a-row>
      <a-row>
        <a-col :span="24">
          <a-form-model-item label="施工安全协议" prop="noticeAnnex">
            <ge-file-new v-model="form.noticeAnnex" :config="{ disabled, json: true }"></ge-file-new>
          </a-form-model-item>
        </a-col>
      </a-row>
      <a-row>
        <a-col :span="24">
          <a-form-model-item label="相关方入厂安全须知" prop="securityAnnex">
            <ge-file-new v-model="form.securityAnnex" :config="{ disabled, json: true }"></ge-file-new>
          </a-form-model-item>
        </a-col>
      </a-row>
    </a-form-model>
    <div class="buttons">
      <a-button type="primary" class="primary" @click="handleSave" style="margin-right: 16px" icon="save"
        v-if="!disabled">保存
      </a-button>
      <a-button type="primary" class="primary" @click="disabled = false" style="margin-right: 16px"
        v-permission="'work_jk_contractor_contractor_qualification_jk_EDIT'" v-else>编辑
      </a-button>
      <a-button class="finish-btn" style="margin-right: 16px" v-if="isDetail && status === 'NOT'" @click="startProject"
        v-permission="'work_jk_contractor_contractor_qualification_jk_EDIT'">开工
      </a-button>
      <a-button class="success-btn" style="margin-right: 16px" v-if="isDetail && status === 'UNDERWAY'"
        @click="completedProject" v-permission="'work_jk_contractor_contractor_qualification_jk_EDIT'">竣工
      </a-button>
      <a-button @click="goBack">取消</a-button>
      <a-modal v-model="visible" :title="(isStart ? '开工' : '竣工') + '确认'" @ok="handleOk" @cancel="cancel" width="440px">
        <a-row type="flex">
          <a-col flex="110px">请确认{{ isStart ? "开工" : "竣工" }}时间</a-col>
          <a-col flex="auto">
            <ge-data-picker-new v-model="projectTime" :config="{ format: 'YYYY-MM-DD HH:mm' }" />
          </a-col>
        </a-row>
      </a-modal>
    </div>
  </div>
</template>

<script>
import Aline from "@/views/environment/pollutionSource/components/Aline.vue";
import TopHead from "@/views/educationTrain/components/TopHead.vue";
import contractorApi from "@/api/work/contractorjk.js";
export default {
  name: "ProjectInfoAdd",
  components: { Aline, TopHead },
  data() {
    return {
      layout: {
        labelCol: { flex: "150px" },
        wrapperCol: { flex: "auto" },
        labelAlign: "left",
        layout: "vertical",
      },
      form: {
        staff: [{}],
        deduct: 0,
        program: "<p></p>",
      }, //表单
      rules: {
        name: {
          required: true,
          message: "请输入承包商项目名称",
          trigger: "blur",
        },
        time: {
          required: true,
          message: "请选择作业计划时间",
          trigger: "change",
        },
        principalPhone: {
          required: true,
          message: "请输入负责人联系电话",
          trigger: "blur",
        },
        principal: {
          required: true,
          message: "请选择现场负责人",
          trigger: "change",
        },
        admissionAnnex: {
          required: true,
          message: "请上传入场施工申请单",
          trigger: "change",
        },
        noticeAnnex: {
          required: true,
          message: "请上传施工安全协议",
          trigger: "change",
        },
        securityAnnex: {
          required: true,
          message: "请上传相关方入厂安全须知",
          trigger: "change",
        },
        staff: {
          required: true,
          message: "请添加作业人员信息",
          trigger: "change",
        },
      }, //校验规则
      disabled: false, //是否禁用
      rowId: null, //评估id
      qualificationId: null, //承包商id
      status: null, //项目状态
      isStart: true, //是否为开工状态
      visible: false,
      projectTime: null, //开工/竣工时间
    };
  },
  computed: {
    // 是否是详情
    isDetail() {
      return this.rowId ? true : false;
    },
    columns() {
      return [
        {
          label: "序号",
          prop: "number",
          width: "30px",
          align: "center",
          render: (h, { props: { row } }) => {
            return <span>{row.rowIndex + 1}</span>;
          },
        },
        {
          label: "姓名",
          prop: "name",
          component: "GeInputNew",
          config: { disabled: this.disabled, size: "default" },
          required: true,
          attrs: {
            placeholder: "请填写姓名",
          },
        },
        {
          label: "手机号",
          prop: "phone",
          component: "GeInputNew",
          config: { disabled: this.disabled, size: "default" },
          required: true,
          attrs: {
            placeholder: "请填写手机号",
          },
        },
        {
          label: "工种",
          prop: "post",
          component: "GeInputNew",
          config: { disabled: this.disabled, size: "default" },
          required: true,
          attrs: {
            placeholder: "请填写工种",
          },
        },
        {
          label: "身份证号",
          prop: "idCard",
          component: "GeInputNew",
          config: { disabled: this.disabled, size: "default" },
          required: true,
          attrs: {
            placeholder: "请填写身份证号",
          },
        },
        {//3月17增加年龄项
          label: "年龄",
          prop: "age",
          component: "GeNumber",
          config: { disabled: this.disabled, size: "default" },
          attrs: {
            placeholder: "请填写年龄",
          },
        },
        {
          label: "本人照片",
          prop: "photo",
          component: "GeImageNew",
          config: {
            disabled: this.disabled,
            size: "small",
            json: true,
            maxLength: 1,
          },
          required: true,
          attrs: {
            placeholder: "请上传本人照片",
          },
          listeners: {
            backValue(val) {
              console.log(val);
            },
          },
        },
        {
          label: "是否为特种人员",
          prop: "isSpecial",
          component: "GeRadioNew",
          required: true,
          config: {
            disabled: this.disabled,
            option: [
              { value: true, label: "是" },
              { value: false, label: "否" },
            ],
          },
        },
        {
          label: "特种人员证书",
          prop: "annex",
          component: "GeFileNew",
          config: {
            disabled: this.disabled,
            multiple: true,
            size: "small",
            json: true,
          },
        },
      ];
    },
  },
  created() {
    let { id, rowId, status } = this.$route.query;
    this.qualificationId = parseInt(id);
    this.$set(this.form, "qualification", this.qualificationId);
    this.rowId = rowId;
    this.status = status;
    if (rowId) {
      this.disabled = true;
      this.getRowDetail();
    }
  },
  methods: {
    valid(val) {
      console.log(val);
    },
    // 开工/竣工
    handleOk() {
      if (!this.projectTime) {
        return this.$message.error("请选择时间！");
      }
      if (this.isStart) {
        contractorApi
          .startProject({
            id: this.rowId,
            startTime: this.projectTime,
          })
          .then((res) => {
            this.$message.success("开工成功！");
            this.handleBack();
          });
      } else {
        contractorApi
          .completedProject({
            id: this.rowId,
            endTime: this.projectTime,
          })
          .then((res) => {
            this.$message.success("竣工成功！");
            this.handleBack();
          });
      }
    },
    // 开工
    startProject() {
      this.isStart = true;
      this.visible = true;
    },
    // 竣工
    completedProject() {
      this.isStart = false;
      this.visible = true;
    },
    // 取消
    cancel() {
      this.visible = false;
      this.projectTime = null;
    },
    // 计算剩余额度
    calculateRemaining() {
      this.form.remaining = this.form.mortgage - this.form.deduct;
    },
    // 子表单新增行
    handleIncrease() {
      this.form.staff.push({});
    },
    // 子表单删除行
    handleDecrease(val) {
      val.forEach((v) => {
        this.form.staff = this.form.staff.filter(
          (f) => f.__ob__.dep.id != v.__ob__.dep.id
        );
      });
    },
    // 获取项目信息详情
    getRowDetail() {
      contractorApi.detailProject(this.rowId).then((res) => {
        let { qualification, endDate, startDate, staff } = res.detail;
        this.form = {
          ...res.detail,
          qualification: qualification.id,
          time: startDate ? [startDate, endDate] : null,
          staff: staff.map((v) => {
            return {
              ...v,
              photo: v.photo ? [v.photo] : [],
            };
          }),
        };
      });
    },
    goBack() {
      if (!this.disabled) {
        this.$confirm("取消后会失去编辑的所有数据。", {
          type: "warning",
        }).then((res) => {
          this.handleBack();
        });
      } else {
        this.handleBack();
      }
    },
    // 返回
    handleBack() {
      this.$router.push({
        name: "contractorCenterDetailJK",
        query: { tab: "project", id: this.qualificationId },
      });
    },
    // 保存
    handleSave() {
      // 将所有的校验结果都处理成promise形式放到队列中
      let validPromise = [];
      // 普通表单校验
      this.$refs.ruleForm.validate((valid) => {
        validPromise.push(
          valid ? Promise.resolve(true) : Promise.resolve(false)
        );
      });
      // 子表单校验
      let childFormValid = true;
      if (this.form.staff.length > 0) {
        this.$refs.childForm.validate((valid) => {
          if (!valid) {
            childFormValid = false;
          }
        });
      } else {
        childFormValid = false;
      }
      validPromise.push(
        childFormValid ? Promise.resolve(true) : Promise.resolve(false)
      );
      // 特种证书校验
      this.form.staff.forEach((item, index) => {
        if (Reflect.get(item, 'isSpecial')) {
          if (Reflect.get(item, 'annex').length) {
            validPromise.push(Promise.resolve(true));
          } else {
            this.$message.error(`请完善序号${index + 1}的特种人员证书信息`);
            validPromise.push(Promise.resolve(false));
          }

        }
      })
      // 判断是否所有的校验都通过
      Promise.all(validPromise).then((reslist) => {
        if (reslist.every((v) => v)) {
          let data = {
            ...this.form,
            qualification: { id: this.form.qualification },
            staff: this.form.staff.map((v) => {
              return {
                ...v,
                photo: v.photo[0],
              };
            }),
          };
          // 编辑
          if (this.isDetail) {
            contractorApi
              .editProject({
                id: this.rowId,
                ...data,
              })
              .then((res) => {
                this.$message.success("编辑成功！");
                this.handleBack();
              });
          } else {
            // 新增
            contractorApi
              .addProject({
                ...data,
              })
              .then((res) => {
                this.$message.success("新增成功！");
                this.handleBack();
              });
          }
        } else {
          return this.$message.error("请完善信息");
        }
      });
    },
  },
};
</script>

<style lang="less" scoped>
.container {
  padding: 0 20px 60px 20px;
}

.success-btn {
  background-color: rgb(0, 198, 104);
  color: #fff;
}

.finish-btn {
  background-color: #ffc61f;
  color: #fff;
}

.ge-form {
  .hint {
    font-size: 12px;
    color: rgba(0, 0, 0, 0.45);
  }

  .ant-row {
    display: flex;
    width: 100%;

    .long-label/deep/.ant-form-item-label {
      line-height: 1.2;
    }

    /deep/.ant-form-item-label {
      overflow: inherit;
      text-align: right;
      padding-right: 10px;
      line-height: 32px;

      label.ant-form-item-required {
        margin-left: 10px;
      }

      label {
        font-weight: 400;
        color: rgba(0, 0, 0, 0.85);

        &::before {
          color: #f56c6c;
          line-height: 1.5;
        }
      }
    }
  }

  .ant-form-item {
    margin-bottom: 10px;
    padding-bottom: 0;

    .el-date-editor.el-input,
    .el-select {
      width: 100%;
    }

    .ant-input {
      margin-bottom: 0;
    }
  }

  .flex {
    display: flex;
    align-items: center;

    >span {
      flex: 0 0 60px;
    }
  }

  .way-box {
    background: rgba(0, 134, 251, 0.04);
    border: 1px solid rgba(0, 0, 0, 0.08);
    padding: 20px 20px 4px 20px;
  }

  /deep/.ge-child-form {
    .child-form-header {
      .title {
        color: rgba(0, 0, 0, 0.85);
      }
    }

    .ant-form-item {
      padding-bottom: 0;
    }
  }

  .radio-box {
    line-height: 32px;
  }

  /deep/.ant-select-selection-selected-value,
  /deep/.ant-select-selection__choice__content {
    color: #222;
  }

  /deep/.ant-form-item-control-wrapper {
    width: 100%;
  }
}

.buttons {
  padding-left: 20px;
  position: fixed;
  bottom: 0;
  z-index: 100;
  height: 50px;
  border: 1px solid #f1f1f1;
  width: 100%;
  background: #ffffff;
  line-height: 50px;
}
</style>